import React, { PureComponent } from 'react';
import { Icon, Col, Select, Button, Form, notification } from 'antd';
import { connect } from 'dva';
import "./form.less"
import "../../Common.less"
class PositionCal extends PureComponent {
    constructor(props) {
        super(props);
        this.state = {
            tdata: [{}],
            roadlist: []
        }
        this.selectRoad = this.selectRoad.bind(this)
        this.addRow=this.addRow.bind(this)
        this.removeRow=this.removeRow.bind(this)
        this.submit=this.submit.bind(this)
        this.validate=this.validate.bind(this)

    }
    async selectRoad(e) {
        console.log(e)
    }
    validate(str){
        let reg=true;
        str=str.replace(/\uff0c/g,",")
        str=str.replace(/\s/g, "")
        if(str.includes(",")){
            let arr=str.split(",");
            const len=arr.length;
            for (let i = 0; i < len; i++) {
                let item = arr[i];
                try {
                    eval(item)
                } catch (error) {
                    reg=false
                }
            }
        }else{
            reg=typeof(str-0)=="number"?true:false
        }
        return reg;
    }
    submit(e){
        e.preventDefault();
        e.stopPropagation();
        const {form,freePoint,modalContext}=this.props;
        const road=form.getFieldValue("road")
        if(!road){
            notification.warn({message:"请选择路线!"})
            return;
        }
        let list=document.querySelectorAll(".tableBoxS tr .input")
        const len=list.length;
        let arr=[]
        let obj={}
        for (let i = 0; i < len; i++) {
            if(i%5==0){
                obj={}
            }
            let node = list[i];
            node.classList.remove("required")
            if(!node.disabled){
                if(!node.value){
                    node.classList.add("required")
                    node.focus()
                    notification.warn({message:"请将字段填写完整!"})
                    return;
                }
                if(node.dataset.validate){
                    if (!this[node.dataset.validate](node.value)) {
                        node.classList.add("required")
                        node.focus()
                        notification.warn({ message: `${node.dataset.name}字段格式不正确!` })
                        return;
                    }
                }
                obj[node.dataset.key]=node.value.replace(/\uff0c/g,",")
                if(i%5==4){
                    arr.push(obj)
                }
            }
        }
        freePoint({freePoints:arr,roadlineId:road},res=>{
            let data=res.data.data;
            if(data&&data.length){
                modalContext.updateModal({
                    visible: true,
                    title: "任意位置坐标计算",
                    footer:null,
                    event: { code: "positionModal" },
                    extra: {
                        tdata:data
                    }
                })
            }
            
        },err=>{

        })
    }
    async componentDidMount() {
        const { project } = this.props;
        let data = await this.props.loadProjectRoads({ projectId: project.id })
        if (data) {
            this.setState({
                roadlist: data.res
            })
        }
    }
    addRow(e,index){
        e.preventDefault();
        let {tdata}=this.state
        tdata.splice(index+1,0,{id:new Date().getTime()})
        this.setState({
            tdata:[...tdata]
        })
        console.log(tdata)
    }
    removeRow(e,index){
        e.preventDefault();
        let {tdata}=this.state
        if(tdata.length<2){
            notification.warn({message:"至少保留一组数据!"})
            return;
        }
        tdata.splice(index,1)
        this.setState({
            tdata:[...tdata]
        })
    }
    render() {
        const { getFieldDecorator } = this.props.form;
        const { roadlist, tdata } = this.state;
        return (
            <div className="positionCal">
                <div>
                    <Col span="12">
                        <Form style={{ padding: "15px 15px" }}
                            layout="inline"
                            labelCol={{ span: 5 }}
                            wrapperCol={{ span: 19 }}

                        >
                            <Form.Item style={{ width: "220px" }} label='路线'>
                                {getFieldDecorator('road', {
                                    rules: [
                                        { required: true, message: '请选择路线' }
                                    ],
                                })(
                                    <Select onSelect={this.selectRoad} placeholder="请选择线路">
                                        {
                                            roadlist.map(item => {
                                                return (
                                                    <Select.Option value={item.id} key={item.id}>{item.name}</Select.Option>
                                                )
                                            })
                                        }

                                    </Select>
                                )}
                            </Form.Item>

                            <Button onClick={this.submit} type="primary" style={{ marginTop: "5px" }}>计算</Button>

                        </Form>
                    </Col>

                </div>
                <div className="tableBoxS tcBox">
                    <table style={{ width: "calc(100% - 30px)", margin: "auto" }}>
                        <tbody>
                            <tr className="th">
                                <td>序号</td>
                                <td>桩号(m)</td>
                                <td>右偏角(度)</td>
                                <td>桩位编号</td>
                                <td>偏心距(m)</td>
                                <td>桩间距(m)</td>
                                {/* <td>X坐标</td>
                                <td>Y坐标</td>
                                <td>方位角</td> */}
                                <td>操作</td>
                            </tr>
                            {
                                tdata && tdata.length ? tdata.map((item,index) => {
                                    return <tr key={'tr'+index}>
                                        <td>{index+1}</td>
                                        <td><input data-key="station" defaultValue="582.180" className="input" type="number" /></td>
                                        <td><input data-key="angle" defaultValue="90" className="input" type="number" /></td>
                                        <td><input data-key="no" defaultValue="1" className="input" type="text" /></td>
                                        <td><input data-key="eccentricity" defaultValue="4.25" className="input" type="number" /></td>
                                        <td><input data-validate="validate" data-key="pileSpacing" defaultValue="0" className="input" type="text" /></td>
                                        {/* <td><input data-key="x" disabled defaultValue={item.x||""}  type="number" /></td>
                                        <td><input data-key="y" disabled defaultValue={item.y||""}  type="number" /></td>
                                        <td><input data-key="azimuth" disabled defaultValue={item.azimuth||""}  type="number" /></td> */}
                                        <td><Icon onClick={e=>this.addRow(e,index)} type="plus-square" /><Icon onClick={e=>this.removeRow(e,index)} type="minus-square" /></td>
                                    </tr>
                                }) : undefined
                            }

                        </tbody>
                    </table>
                    
                </div>
            </div>
        );
    }
}

export default connect(
    ({
        project: { current }
    }) => {
        return { project: current };
    },
    dispatch => ({
        loadProjectRoads: (values) => dispatch({
            type: 'refRoads/loadProjectRoads',
            payload: values
        }),
        freePoint: (values, onSuccess, onError) => dispatch({
            type: 'calculate/freePoint',
            payload: {
                values,
                onSuccess,
                onError

            }
        })

    })
)(Form.create('PositionCal', {

})(PositionCal));